package com.iclub.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.iclub.model.ServiceException;
import com.iclub.util.GlobalParamUtil;



/**
 * 
 * @description: 请求参数是否有效的拦截器
 */
public class IClubCheckRequestDataFilter implements Filter{
	
	private  Logger log_detail = Logger.getLogger("DETAIL");

	/**
	 * 循环参数校验
	 * desc:
	 * @param funcode
	 * @param request
	 * @return
	 */
	public boolean checkParameters(String funcode, HttpServletRequest request) {
		String keys = GlobalParamUtil.getGlobalParam(funcode);
		if ("".equals(keys)) {
			log_detail.info(String.format("Service %s found no check info",
					funcode));
			return true;
		}
		log_detail.info(String.format("funCode[%s] request parameters checked by regex beginning", funcode));
		// 校验规则以$分隔
		String[] chkKeys = keys.split("\\$");
		for (String key : chkKeys) {
			String[] regConfigs = key.split("\\|");
			// 参数校验配置错误
			if (null == regConfigs || regConfigs.length != 2) {
				log_detail.error("service interface regex config :" + regConfigs);
				return false;
			}
			// first key
			String param_key = regConfigs[0];
			// second regex
			String regex = regConfigs[1];
			// check key is empty
			if ("".equals(param_key)) {
				log_detail.warn(String.format("request parameter no config key", key));
    			continue;
    		}
			// check regex is empty
			if ("".equals(regex)) {
				log_detail.warn(String.format("request parameter %s found no regex info", key));
				continue;
			}
			 // check is not must do
            boolean must = isOptional(param_key);
            // not must do remove []
            if(must){
            	param_key = removBrackets(param_key);
            }
            //  geting request parameter
            String param_value = trim(request.getParameter(param_key));
            // second request attributte
            if("".equals(param_value)){
            	param_value = trim(request.getAttribute(param_key));
            }
            // checking value
            boolean checkResult = check(param_key,param_value,must,regex);
            // check result
    		if(checkResult) {
    			continue;
    		} else {
    			return false;
    		}
		}
		log_detail.info(String.format("funCode[%s] request parameters checked by regex success", funcode));
		return true;
	}
	/**
	 * 参数合法性验证
	 * desc:
	 * @param key
	 * @param value
	 * @param must
	 * @param regex
	 * @return
	 */
	protected boolean check(String key, String value, boolean must,String regex) {
		if ("".equals(value)) {
			// 必须字段为空，抛出异常
			if (!must) {
				log_detail.warn(String.format("must request parameter [%s] value is empty", key));
				return false;
			}
		} else {
            // 去掉空格字符
            value = value.replaceAll("\\s*","");
			// 不符合正则表达式
			if (!value.matches(regex)) {
				log_detail.warn(String.format("request parameter [%s] value[%s] is not match regex[%s]", key,value,regex));
				return false;
			}
		}
		return true;
	}
	// remove start[ and end ]
	private String removBrackets(String key) {
		return key.substring(1, key.length() - 1);
	}
	// check is must or not
	private boolean isOptional(String key) {
		return key.startsWith("[") && key.endsWith("]");
	}
	// remove space char
	protected String trim(Object src) {
		return src == null ? "" : src.toString().trim();
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request = (HttpServletRequest) req;  
        HttpServletResponse response = (HttpServletResponse) resp;  
		// 请求应用路径
		String uri = request.getRequestURI();
		// 请求接口名称
		String funCode = trim(uri.substring(uri.lastIndexOf("/")+1));
		log_detail.info("用户输入参数校验"+funCode);
		if(!"".equals(trim(funCode))){
			if(checkParameters(funCode,request)){
				chain.doFilter(request, response);
			}else{
				request.getRequestDispatcher("/common/argsError.to").forward(request, response);
			}
		}
		chain.doFilter(request, response);
	
	}
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
	
}
